#include "MQTTClient.h"
#include "app_mqtt.h"
#include "log.h"

// MQTT 句柄
static MQTTClient mqtt_client;

// 初始化一个连接参数的模板
// 这个是什么意思  还没有 弄清楚
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; 

// 初始化一个消息的模板
static MQTTClient_message pubmsg = MQTTClient_message_initializer;

// 外部程序注册在消息队列模块的回调，该回调负责数据接收后的实际处理
static int (*app_mqtt_callback_func)(char *data ,int len);

// 失联函数
void app_mqtt_connectionLost(void *context, char *cause)
{
    // 打印失联原因
    log_error("connection lost: %s",cause);
    // 直接 销毁  先断开连接
    MQTTClient_disconnect(mqtt_client,1000);
    MQTTClient_destroy(&mqtt_client);
}

// 消息到达函数
int app_mqtt_messageArrived(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    // 消息到达之后   将数据内容提取出来
    char *data = message->payload;
    char data_len = message->payloadlen;

    // 利用外部注册的回调函数  进行数据处理
    int res = app_mqtt_callback_func(data,data_len);
    if (res < 0)
    {
        // 后续处理失败
        return 0;
    }
    // 处理成功返回1
    return 1;
}

// 发送成功回掉
void app_mqtt_deliveryComplete(void *context, MQTTClient_deliveryToken dt)
{
    log_info("data is send Complete  succ");
}


// 初始化MQTT客户端
/**
 * 要实现的功能
 * 1. mqtt客户端创建
 * 2. 客户端回掉方法的注册 
 * 3. mqtt客户端要连接服务器（init方法）
 * 4. mqtt要主动订阅某个主题（subscribe方法）
 */
int app_mqtt_init(void)
{
    // 客户端的创建
    int res = MQTTClient_create(&mqtt_client,MQTTCLIENT_URL,MQTTCLIENT_ID,MQTTCLIENT_PERSISTENCE_NONE,NULL);
    if (res != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_create error");
        return -1;
    }
    // 回掉方法的注册
    MQTTClient_setCallbacks(mqtt_client,NULL,app_mqtt_connectionLost,app_mqtt_messageArrived,app_mqtt_deliveryComplete);
    
    // mqtt 客户端要连接服务器（init方法）
    res = MQTTClient_connect(mqtt_client,&conn_opts);
    if (res != MQTTCLIENT_SUCCESS)
    {
        MQTTClient_destroy(&mqtt_client);
        log_error("connect error");
        return -1;
    }
    // mqtt 要主动订阅某个主题（subscribe方法）
    res = MQTTClient_subscribe(mqtt_client,MQTTCLIENT_SUBSCRIBE_TOPIC,MQTTCLIENT_QOS);
    if (res != MQTTCLIENT_SUCCESS)
    {
        MQTTClient_destroy(&mqtt_client);
        log_error("subscribe error");
        return -1;
    }
    
    
    return 0;
}

// 发布消息
int app_mqtt_send(char *data ,int len)
{
    // 设置要发送的消息选项
    pubmsg.payload = data;
    pubmsg.payloadlen = len;
    pubmsg.qos = MQTTCLIENT_QOS;

    // 发送消息 发送数据到服务器上
    int res = MQTTClient_publishMessage(mqtt_client,MQTTCLIENT_PUBLISH_TOPIC,&pubmsg,NULL);

    if (res != MQTTCLIENT_SUCCESS)
    {
        log_error("publishMessage error");
        return -1;
    }
    return 0;
    
}

// 注册接受数据后的处理
int app_mqtt_register_recv(int (*callback)(char *data ,int len))
{
    app_mqtt_callback_func = callback;
    return 0;
}

// 销毁MQTT客户端
void app_mqtt_destroy(void)
{
    // 销毁之前，先断开连接!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    MQTTClient_disconnect(mqtt_client,1000);
    MQTTClient_destroy(&mqtt_client);
}